﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Web;

namespace ConsoleApp
{
    class Program
    {
        static System.Timers.Timer timer = null;
        static int time = 120;
        static void Main(string[] args)
        {
            Console.WriteLine($"Main Start {Thread.CurrentThread.ManagedThreadId:00}");

            init();

            //最终执行的
            Console.WriteLine($"Main End {Thread.CurrentThread.ManagedThreadId:00}");
            Console.ReadKey();
        }

        protected static void init()
        {
            //GetTimer();

            //GetDecrypt();

            //GetTask();

            //GetTaskAsync();

            //GetTaskTest();

            //GetInvoiceDEScrypt();

            //GetInvoiceDESEncrypt();

            GetInvoiceRespone();
        }

        protected static void GetTimer()
        {
            #region MyRegion

            /*timer = new Timer();
            timer.Enabled = true;
            timer.Interval = 1000; //执行间隔时间,单位为毫秒; 这里实际间隔为10分钟  
            timer.Start();
            timer.Elapsed += new ElapsedEventHandler(test);

            Console.ReadKey();*/

            /*var xmlInfo = @"<?xml version='1.0' encoding='gbk'?>    
                            <RoomFolio>  
                                <Rows>  
                                    <Row>
                                        <RegId>0002501316</RegId>
                                        <RoomNo>0602</RoomNo>
                                        <GuestCname>迟付账测试</GuestCname>
                                        <ArrDate>2019-07-29 09:28:00</ArrDate>
                                        <Payment></Payment>
                                        <isTransfer>1</isTransfer>
                                        <ExcutiveRate>298</ExcutiveRate>
                                        <Balance>1296</Balance>
                                        <ApprovalAmt>0</ApprovalAmt>
                                        <EnableAmount>1296</EnableAmount>
                                        <WqPersons>0</WqPersons>
                                        <PhotoUrl>
                                        </PhotoUrl>
                                    </Row>  
                                </Rows>
                            </RoomFolio>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlInfo);

            List<HouseXmlNodeResult> list = new List<HouseXmlNodeResult>();

            XmlNodeList topM = doc.SelectNodes("//Row");
            foreach (XmlElement element in topM)
            {
                var item = new HouseXmlNodeResult()
                {
                    RegId = element.GetElementsByTagName("RegId")[0].InnerText,
                    RoomNo = element.GetElementsByTagName("RoomNo")[0].InnerText,
                    GuestCname = element.GetElementsByTagName("GuestCname")[0].InnerText,
                    ArrDate = element.GetElementsByTagName("ArrDate")[0].InnerText,
                    Payment = element.GetElementsByTagName("Payment")[0].InnerText,
                    isTransfer = element.GetElementsByTagName("isTransfer")[0].InnerText,
                    ExcutiveRate = element.GetElementsByTagName("ExcutiveRate")[0].InnerText,

                    //关于金额需要特殊处理一下 2019-08-07
                    Balance = (element.GetElementsByTagName("Balance").Count > 0 ? element.GetElementsByTagName("Balance")[0].InnerText : "0"),
                    ApprovalAmt = (element.GetElementsByTagName("ApprovalAmt").Count > 0 ? element.GetElementsByTagName("ApprovalAmt")[0].InnerText : "0"),
                    ApprovalAdj = (element.GetElementsByTagName("ApprovalAdj").Count > 0 ? element.GetElementsByTagName("ApprovalAdj")[0].InnerText : "0"),
                    LimitAmount = (element.GetElementsByTagName("LimitAmount").Count > 0 ? element.GetElementsByTagName("LimitAmount")[0].InnerText : "0"),
                    Chargeamt = (element.GetElementsByTagName("Chargeamt").Count > 0 ? element.GetElementsByTagName("Chargeamt")[0].InnerText : "0"),
                    EnableAmount = (element.GetElementsByTagName("EnableAmount").Count > 0 ? element.GetElementsByTagName("EnableAmount")[0].InnerText : "0"),
                    Remark = (element.GetElementsByTagName("Remark").Count > 0 ? element.GetElementsByTagName("Remark")[0].InnerText : ""),
                    CashRemark = (element.GetElementsByTagName("CashRemark").Count > 0 ? element.GetElementsByTagName("CashRemark")[0].InnerText : ""),
                    WqPersons = (element.GetElementsByTagName("WqPersons").Count > 0 ? element.GetElementsByTagName("WqPersons")[0].InnerText : ""),
                    Cerid = (element.GetElementsByTagName("Cerid").Count > 0 ? element.GetElementsByTagName("Cerid")[0].InnerText : ""),
                    PhotoUrl = (element.GetElementsByTagName("PhotoUrl").Count > 0 ? element.GetElementsByTagName("PhotoUrl")[0].InnerText : "")
                };

                list.Add(item);
            }

            Console.WriteLine(new JavaScriptSerializer().Serialize(list));
            Console.ReadLine();*/

            #endregion
        }

        protected static void GetDecrypt()
        {
            Console.WriteLine(CryptHelper.DecryptDES("JekU5x1j+17mBuir4pFcNg=="));
        }

        protected static void GetTask()
        {
            Console.WriteLine($"加密内容：JekU5x1j+17mBuir4pFcNg==");
            Task.Run(() =>
            {
                Console.WriteLine($"Run Thread Sleep 3000 before {Thread.CurrentThread.ManagedThreadId:00}");
                Thread.Sleep(5000);
                Console.WriteLine($"Run Thread Sleep 3000 after {Thread.CurrentThread.ManagedThreadId:00}");
            });
            Console.WriteLine($"解密内容：{CryptHelper.DecryptDES("JekU5x1j + 17mBuir4pFcNg == ")}");
        }

        protected static async void GetTaskAsync()
        {
            Console.WriteLine($"加密内容：JekU5x1j+17mBuir4pFcNg==");
            await Task.Run(() =>
            {
                Console.WriteLine($"Run Thread Sleep 3000 before {Thread.CurrentThread.ManagedThreadId:00}");
                Thread.Sleep(3000);
                Console.WriteLine($"Run Thread Sleep 3000 after {Thread.CurrentThread.ManagedThreadId:00}");
            });
            Console.WriteLine($"解密内容：{CryptHelper.DecryptDES("JekU5x1j + 17mBuir4pFcNg == ")}");
        }

        protected static void GetTaskTest()
        {
            Task t = new Task(() =>
            {
                Console.WriteLine("任务开始工作……");
                //模拟工作过程
                Thread.Sleep(5000);
            });
            t.Start();
            t.ContinueWith((task) =>
            {
                Console.WriteLine("任务完成，完成时候的状态为：");
                Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
            });
            Console.ReadKey();
        }

        protected static void GetInvoiceDEScrypt()
        {
            string type = "1";//授权类型 1 m3秘钥授权 2 token交换授权
            string returnpage = "mt3consumelist";//默认跳转到消费列表
            string hid = "000010";//酒店ID
            string md = "5EE6229EEEE83D53C01D0508CE975124C6326D7465AFEF127D17A5FDCEFA50A14305FEDFF7C98BACC01D0508CE975124B45B762D78429C11B6632D5549F2A1BF51816B7661E5310F118F0A70BF37D957A3885C3B43DB38A40BC8AC9682562CAE0C689526DC7AC4AB16107F5143090424F592BDA55741F731DD69661E0F522FD5143C6EF8C8E69A8798BD93E7FE0261304A8466488AC075E21F9BC8A39733CD27637DF5436DEB4885F1DDF05FA00249CDD977D340BECFCF2B5F4DB57A2FE68138488A5A58762DE21F22076D9C6C107C4B619B8EBDFDB8260F1953EE447DC3ECBEA0B0187FDD7648382282243A89EA124E306E344ABCD590A179AD6DE6C2B919B887E6B964E6B369BA941A0C3F054B83B5020C2FB5E0E749CCB8B79ABCC614DF1596B35AD442FA7610C5FA2634E1B389C7CA7CDD1912D14233297DED639C4F878E0BC8AC9682562CAEFACAE6D9D0ED540C969D9B8ABA951E79351E6DF4D1B23326C9B540B52C106C3B3EDDFBD878481F09BEA37C7EE11635CD";//加密字符串
            string tm = "20190802100501";//时间字符串

            if (type == "1")
            {
                try
                {
                    string InvoiceThirdKey = "JXD12345";
                    string decodestring = "";
                    InvoiceThirdKey = InvoiceThirdKey.PadRight(8, '0');
                    if (InvoiceThirdKey.Length > 8)
                    {
                        InvoiceThirdKey = InvoiceThirdKey.Substring(0, 8);
                    }
                    decodestring = DESEncrypt.Decrypt(md, InvoiceThirdKey);//解密字符串
                    decodestring = HttpUtility.UrlDecode(decodestring);
                    Console.WriteLine(decodestring);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        protected static void GetInvoiceDESEncrypt()
        {
            string key = "v.gshis.com".Substring(0, 8);
            CustomerInfo ct3 = new CustomerInfo()
            {
                hid = "000825",
                resid = "000825201903310001",
                guestname = "新预订客人"
            };
            string jsonStr = "{\"hid\":\"000825\",\"resid\":\"000825201910290001\",\"guestname\":\"韩国语\"}";
            jsonStr = JsonConvert.SerializeObject(ct3);
            string encodeStr = HttpUtility.UrlEncode(jsonStr);
            var result = DESEncrypt.Encrypt(encodeStr, key);
            Console.WriteLine(result);
            GetInvoiceDESDecrypt(result);
        }

        protected static void GetInvoiceDESDecrypt(string jsonStr)
        {
            string key = "v.gshis.com".Substring(0, 8);
            var result = DESEncrypt.Decrypt(jsonStr, key);
            result = HttpUtility.UrlDecode(result);
            Console.WriteLine(result);
        }

        protected static void GetInvoiceRespone()
        {
            var para = $"hid=000825&resid=000825201903310001&guestname=新预订客人";
            var data = Encoding.UTF8.GetBytes(para);

            var request = WebRequest.CreateHttp($"http://v.gshis.com/InvoiceApi/GetCT3InvoiceUrl?" + para);
            request.Method = "POST";
            request.ContentType = "application/json";
            using (var input = request.GetRequestStream())
            {
                input.Write(data, 0, data.Length);
            }
            using (var response = request.GetResponse())
            {
                Stream stream = response.GetResponseStream();   //获取响应的字符串流
                StreamReader sr = new StreamReader(stream); //创建一个stream读取流
                string res = sr.ReadToEnd();   //从头读到尾，放到字符串html
                Hashtable ret = JsonConvert.DeserializeObject<Hashtable>(res);
                
                Console.WriteLine(res);
            }
        }

        protected static void test(object source, ElapsedEventArgs e)
        {
            if (time <= 0)
            {
                timer.Stop();
            }
            else
            {
                time--;
                Console.WriteLine(time.ToString());
            }
        }

        #region DES加密解密
        public static class DESEncrypt
        {
            /// <summary>
            /// 加密
            /// </summary>
            /// <param name="stringToEncrypt"></param>
            /// <param name="sKey"></param>
            /// <returns></returns>
            public static string Encrypt(string stringToEncrypt, string sKey)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(stringToEncrypt);
                des.Key = ASCIIEncoding.UTF8.GetBytes(sKey);
                des.IV = ASCIIEncoding.UTF8.GetBytes(sKey);
                des.Mode = CipherMode.ECB;
                des.Padding = PaddingMode.ISO10126;
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
                return ret.ToString();
            }
            /// <summary>
            /// 解密
            /// </summary>
            /// <param name="stringToDecrypt"></param>
            /// <param name="sKey"></param>
            /// <returns></returns>
            public static string Decrypt(string stringToDecrypt, string sKey)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                byte[] inputByteArray = new byte[stringToDecrypt.Length / 2];
                for (int x = 0; x < stringToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(stringToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                des.Key = ASCIIEncoding.UTF8.GetBytes(sKey);
                des.IV = ASCIIEncoding.UTF8.GetBytes(sKey);
                des.Mode = CipherMode.ECB;
                des.Padding = PaddingMode.ISO10126;
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret = new StringBuilder();

                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
        }
        #endregion

        private class HouseXmlNodeResult
        {
            public string RegId { get; set; }
            public string RoomNo { get; set; }
            public string GuestCname { get; set; }
            public string ArrDate { get; set; }
            public string Payment { get; set; }
            public string isTransfer { get; set; }
            public string ExcutiveRate { get; set; }
            public string Balance { get; set; }
            public string ApprovalAmt { get; set; }
            public string ApprovalAdj { get; set; }
            public string LimitAmount { get; set; }
            public string Chargeamt { get; set; }
            public string EnableAmount { get; set; }
            public string Remark { get; set; }
            public string CashRemark { get; set; }
            public string WqPersons { get; set; }
            public string Cerid { get; set; }
            public string PhotoUrl { get; set; }
        }

        public class CustomerInfo
        {
            public string hid { get; set; }
            public string resid { get; set; }
            public string guestname { get; set; }
        }
    }
}
